/*
 * Copyright 2000-2020 ALPHA LAB.Inc All Rights Reserved.
 */
package com.moonlight.demo.test;

import java.io.BufferedReader;  
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map; 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet; 
import org.apache.log4j.Logger; 
import net.sf.json.JSONObject; 

/**
 * 合并项目全部requirejs文件的servlet，服务器启动后调用.
 * @author allen 
 * @version 1.0.0 2018年2月1日
 */
public class DynamicAmdServlet extends HttpServlet  {
	
	private static final Logger logger = Logger.getLogger(DynamicAmdServlet.class);  
	
	public void init() throws ServletException {
		/**
		 * 1.获取全部amdconfig文件
		 */
		//获取web项目根目录路径
//		String baseUrl = config.getServletContext().getContextPath();
//		URL baseUrl = DynamicAmdServlet.class.getResource("/"); 
//		String baseUrl = this.getServletContext().getRealPath("/");
		
		//直接通过http的地址访问webcore目录下的amdconfig文件，需要在服务器启动完之后调用定时器执行
		URL url = null;
		try {
			url = new URL("http://localhost:9080/moonlight.demo/webcore/scripts/amdconfig/amd.config.js");
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			InputStream is = url.openStream();
			//将字节输入流转换为字符输入流
			InputStreamReader isr = new InputStreamReader(is,"UTF-8");
			BufferedReader br = new BufferedReader(isr);
			String res = "";
			String line = "";
			//读取数据
			while((line=br.readLine())!=null){
				res+=line;
			}
			br.close();
			isr.close();
			is.close();
			System.out.println(res);
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
		/**
		 * 2.将文件流解析为字符串
		 */
		
		/**
		 * 3.将字符串转成json对象
		 */
		
		/**
		 * 4.将json对象封装成新json对象
		 */
		
		/**
		 * 5.将新json对象解析成字符串，写到新文件中 
		 */
		
		
		//test代码如下
		//1.将文件流解析为字符串
		String jsContent1 = "require.config({'paths':{'moduleA':'/grm/appraise/scripts/aconst1'},'shim':{'angular1':'/grm/appraise/scripts/angular1'}});";
		String jsContent2 = "require.config({'paths':{'moduleB':'/grm/appraise/scripts/aconst2','moduleC':'/grm/appraise/scripts/aconst3'},'shim':{'angular2':'/grm/appraise/scripts/angular2'}});";
		
		String jsFormatStr1 = getJsonContent(jsContent1);
		String jsFormatStr2 = getJsonContent(jsContent2);
		
		//2.将字符串转成json对象
		JSONObject jsContentObj1 = JSONObject.fromObject(jsFormatStr1);
		JSONObject jsContentObj2 = JSONObject.fromObject(jsFormatStr2); 
		
		//3.将json对象封装成新对象
		JSONObject comboContent = new JSONObject();  
		
		JSONObject comboContentPath = new JSONObject();
		
		List<JSONObject> allPathObjs = new ArrayList<JSONObject>();
		JSONObject pathObjs1 = jsContentObj1.getJSONObject("paths");
		JSONObject pathObjs2 = jsContentObj2.getJSONObject("paths");
		allPathObjs.add(pathObjs1);
		allPathObjs.add(pathObjs2);
		
		for (JSONObject pathObj : allPathObjs) {  
			if (pathObj != null) {
		        Iterator it = pathObj.entrySet().iterator();
		        String value = null;
		        String key = null;
		        while (it.hasNext()) {
		          Map.Entry entry = (Map.Entry)it.next();
		          value = (String)entry.getValue();
		          key = (String)entry.getKey();
		          if (value != null) {
		        	  comboContentPath.put(key,  value);
		          }
		        }	  
			} 
		} 
		//添加path属性
		comboContent.put("paths", comboContentPath); 
		
		JSONObject comboContentShim = new JSONObject();
		
		List<JSONObject> allShimObjs = new ArrayList<JSONObject>();
		JSONObject shimObjs1 = jsContentObj1.getJSONObject("shim");
		JSONObject shimObjs2 = jsContentObj2.getJSONObject("shim");
		allShimObjs.add(shimObjs1);
		allShimObjs.add(shimObjs2);
		
		for (JSONObject pathObj : allShimObjs) {  
			if (pathObj != null) {
		        Iterator it = pathObj.entrySet().iterator();
		        String value = null;
		        String key = null;
		        while (it.hasNext()) {
		          Map.Entry entry = (Map.Entry)it.next();
		          value = (String)entry.getValue();
		          key = (String)entry.getKey();
		          if (value != null) {
		        	  comboContentShim.put(key,  value);
		          }
		        }	  
			} 
		} 
		//添加shim属性
		comboContent.put("shim", comboContentShim);  
		
		//4.将json对象解析成字符串，写到新文件中 
		String configFileStr = "require.config(" + comboContent + ");";
		System.out.println(configFileStr);
		
		//5.新文件放到webapp目录下，新建webcore-script目录，然后放置文件		
		

		
		
	}
	
	public static String getJsonContent(String content) {
		if (content == null) {
			return null;
		}
		int fistPos = content.indexOf("{");
		int lastPos = content.lastIndexOf("}");
		String result = content.substring(fistPos, lastPos + 1);

		result = result.replaceAll("(?<!:)\\/\\/.*|\\/\\*(\\s|.)*?\\*\\/", "");
		return result;
	}		
	
	 
}
